package utilities;

import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

import resources.GlobalSettings;

public class TransformUtilities {

	public static void zoomFit ( AffineTransform transform, Rectangle2D objectRectangle, Rectangle2D componentRectangle )
	{
		// First we need to reset and translate the graph to the viewport's center
		transform.setToIdentity( );
		transform.translate( Math.round( componentRectangle.getWidth( ) / 2.0 ), Math.round( componentRectangle.getHeight( ) / 2.0 ) );
		
		// We need to fit it to the viewport. So we want to scale according to the lowest viewport-to-graph dimension ratio.
		double widthRatio = ( componentRectangle.getWidth( ) - GlobalSettings.zoomPadding ) / objectRectangle.getWidth( );
		double heightRatio = ( componentRectangle.getHeight( ) - GlobalSettings.zoomPadding ) / objectRectangle.getHeight( );
		double minRatio = Math.min( widthRatio, heightRatio );
		
		if( minRatio < 1 )
			transform.scale( minRatio, minRatio );
		
		// Only now that we've properly scaled can we translate to the graph's center
		Point2D.Double graphCenter = new Point2D.Double( objectRectangle.getCenterX( ), objectRectangle.getCenterY( ) );
		transform.translate( Math.round( -graphCenter.x ), Math.round( -graphCenter.y ) );
	}
}
